package com.upup.train_management.service.impl;

import com.upup.train_management.entity.Route;
import com.upup.train_management.entity.RouteStation;
import com.upup.train_management.entity.Station;
import com.upup.train_management.repository.RouteRepository;
import com.upup.train_management.repository.RouteStationRepository;
import com.upup.train_management.repository.StationRepository;
import com.upup.train_management.service.RouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RouteServiceImpl implements RouteService {

    private final RouteRepository routeRepository;
    private final RouteStationRepository routeStationRepository;
    private final StationRepository stationRepository;

    @Autowired
    public RouteServiceImpl(
            RouteRepository routeRepository,
            RouteStationRepository routeStationRepository,
            StationRepository stationRepository) {
        this.routeRepository = routeRepository;
        this.routeStationRepository = routeStationRepository;
        this.stationRepository = stationRepository;
    }

    @Override
    public List<Route> getAllRoutes() {
        return routeRepository.findAll();
    }

    @Override
    public Route getRouteById(Long id) {
        return routeRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional
    public Route saveRoute(Route route) {
        return routeRepository.save(route);
    }

    @Override
    @Transactional
    public void deleteRoute(Long id) {
        // 删除路线站点关联数据
        List<RouteStation> routeStations = routeStationRepository.findByRouteIdOrderByStationOrder(id);
        routeStationRepository.deleteAll(routeStations);

        // 删除路线
        routeRepository.deleteById(id);
    }

    @Override
    public List<Route> getRoutesByStartStation(Long startStationId) {
        return routeRepository.findByStartStationId(startStationId);
    }

    @Override
    public List<Route> getRoutesByEndStation(Long endStationId) {
        return routeRepository.findByEndStationId(endStationId);
    }

    @Override
    public List<Route> searchRoutes(Long startStationId, Long endStationId) {
        return routeRepository.findByStartStationIdAndEndStationId(startStationId, endStationId);
    }

    @Override
    public List<Station> getStationsInRoute(Long routeId) {
        List<RouteStation> routeStations = routeStationRepository.findByRouteIdOrderByStationOrder(routeId);
        List<Station> stations = new ArrayList<>();

        for (RouteStation rs : routeStations) {
            stationRepository.findById(rs.getStationId()).ifPresent(stations::add);
        }

        return stations;
    }

    @Override
    @Transactional
    public void addStationToRoute(RouteStation routeStation) {
        // 检查车站是否已经在路线中
        RouteStation existing = routeStationRepository.findByRouteIdAndStationId(
                routeStation.getRouteId(), routeStation.getStationId());

        if (existing == null) {
            // 保存新的路线站点关联
            routeStationRepository.save(routeStation);
        }
    }

    @Override
    @Transactional
    public void removeStationFromRoute(Long routeId, Long stationId) {
        RouteStation routeStation = routeStationRepository.findByRouteIdAndStationId(routeId, stationId);
        if (routeStation != null) {
            routeStationRepository.delete(routeStation);
        }
    }

    @Override
    @Transactional
    public void updateRouteStationOrder(Long routeId, Long stationId, Integer newOrder) {
        RouteStation routeStation = routeStationRepository.findByRouteIdAndStationId(routeId, stationId);
        if (routeStation != null) {
            routeStation.setStationOrder(newOrder);
            routeStationRepository.save(routeStation);
        }
    }

    @Override
    public Double calculateRouteDistance(Long routeId) {
        List<RouteStation> routeStations = routeStationRepository.findByRouteIdOrderByStationOrder(routeId);
        if (routeStations.isEmpty()) {
            return 0.0;
        }

        // 获取最后一个站点的距离，即为全程距离
        return routeStations.get(routeStations.size() - 1).getDistanceFromStart();
    }

    @Override
    public List<Route> searchRoutesByCity(String startCity, String endCity) {
        // 首先查找指定城市的所有车站
        List<Station> startStations = stationRepository.findByCityName(startCity);
        List<Station> endStations = stationRepository.findByCityName(endCity);

        if (startStations.isEmpty() || endStations.isEmpty()) {
            return new ArrayList<>();
        }

        // 提取车站ID
        List<Long> startStationIds = startStations.stream()
                .map(Station::getId)
                .collect(Collectors.toList());

        List<Long> endStationIds = endStations.stream()
                .map(Station::getId)
                .collect(Collectors.toList());

        // 查找匹配的路线
        return routeRepository.findByStartStationIdInAndEndStationIdIn(startStationIds, endStationIds);
    }

    @Override
    public List<Route> getMostPopularRoutes(Integer limit) {
        // 此处需要实现一个复杂查询，找出最受欢迎的路线（基于票的销售量）
        // 如果数据库支持此类查询，可以使用
        try {
            return routeRepository.findMostPopularRoutes(limit);
        } catch (Exception e) {
            // 简化版本，如果上面的查询不可用，我们可以假设暂时返回所有路线
            List<Route> allRoutes = routeRepository.findAll();
            return allRoutes.stream()
                    .limit(limit)
                    .collect(Collectors.toList());
        }
    }
}